<?php

declare(strict_types=1);

namespace App\Middleware\AdminApi;

use Hyperf\Utils\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Service\SysNodeService;
use App\Utils\CustomUtils;
use App\Constants\XZXResponseCode;
use App\Exception\XZXValidationException;
use Hyperf\Di\Annotation\Inject;


class NodeAccessMiddleware implements MiddlewareInterface
{
    /**
     * @Inject()
     * @var SysNodeService
     */

    private $SysNodeService;

    // public function __construct(HttpResponse $response, SysNodeService $SysNodeService)
    // {
    //     // parent::__construct($response, $jwt);
    // }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (!env("ADMIN_NODE_ACCESS_CHECK", true)) {
            // 未开启节点权限验证
            return $handler->handle($request);
        }
        $ext = $request->getAttribute("ext");
        $isSuperRole = $ext['isSuperRole'];
        $roleId = $ext['roleId'];
        CustomUtils::xzxDebug($isSuperRole);
        // 如果是超管，直接放行
        if ($isSuperRole) {
            return $handler->handle($request);
        }

        // 两段需要都取出来
        $requestUrl = CustomUtils::getRequestUri();
        $urlSecond = '/' . substr($requestUrl,strripos($requestUrl,"/") + 1 );

        $requestUrl = str_replace($urlSecond, '', $requestUrl);
        $urlFirst = '/' . substr($requestUrl,strripos($requestUrl,"/") + 1 );

        $url = $urlFirst . $urlSecond;

        // 先匹配2段
        $result = $this->SysNodeService->hasUrlNode($url);
        if (!$result) {
            // 路由压根不存在
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::ROUTE_NOT_FOUND));
        } else {
            // 不存在配置, 则匹配一级
//            $url = $urlFirst;
            $result = $this->SysNodeService->checkRole($url, $roleId);
            if(!$result) {
                //无此请求url的权限
                throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::NO_ACCESS_NODE_CODE));
            }
        }

        return $handler->handle($request);
    }
   
}
